import logging
import math
import wx

import pyciv.bufferedpanel
import pyciv.hexagon
import pyciv.layers

SQRT_OF_THREE = math.sqrt(3.0)
SQRT_OF_THREE_DIVIDED_BY_TWO = SQRT_OF_THREE / 2.0

"""
Internal hex relation
-----x----|
|         |
|         |
y      __/
|   __/ 
|__/
y = x * 2 / sqrt(3)

Conversion between x,y to a,b,c
 a = (x + (y / sqrt(3))) / 2
 b = y / sqrt(3)
 c = (x - (y / sqrt(3))) / 2
can also be simplified to
 a = (x + b) / 2
 c = (x - b) / 2
and remember that a = b + c

Conversion between a,b,c to x,y
 x = a + c
 y = b * sqrt(3)
"""
SCALE = 30.0
INSIDE_SCALE = 30

class MapPanel(pyciv.bufferedpanel.BufferedPanel):
    class Layout():
        def __init__(self, hex, (xd, yd)):
            x = float(hex[0] + hex[2]) * SCALE
            y = float(hex[1] * SQRT_OF_THREE * SCALE)
            self.center = (x + xd, y + yd)
            self.points = ((self.center[0] + INSIDE_SCALE, 
                            self.center[1] - INSIDE_SCALE / SQRT_OF_THREE),
                           (self.center[0] + INSIDE_SCALE, 
                            self.center[1] + INSIDE_SCALE / SQRT_OF_THREE),
                           (self.center[0], 
                            self.center[1] + INSIDE_SCALE * 2.0 / SQRT_OF_THREE),
                           (self.center[0] - INSIDE_SCALE, 
                            self.center[1] + INSIDE_SCALE / SQRT_OF_THREE),
                           (self.center[0] - INSIDE_SCALE, 
                            self.center[1] - INSIDE_SCALE / SQRT_OF_THREE),
                           (self.center[0], 
                            self.center[1] - INSIDE_SCALE * 2.0 / SQRT_OF_THREE)
                           )

    def __init__(self, hexes, layers, *args, **kwargs):
        pyciv.bufferedpanel.BufferedPanel.__init__(self, *args, **kwargs) 

        self._layers = layers
        self._hexes = hexes
        self._origo_position = map(lambda x:x / 2, 
                                   self.GetClientSizeTuple())
        self._generate_layout(self._hexes)
        
        self.on_size(None)

        
    def _generate_layout(self, hexes):
        self._layout = {}
        for hex in hexes:
            self._layout[hex] = MapPanel.Layout(hex, self._origo_position)

    def draw(self, dc):
        dc.SetBackground(wx.LIGHT_GREY_BRUSH)
        dc.Clear()
        for layer in self._layers:
            layer.render(dc, self._hexes, self._layout)
        self.dirty_hexes = []

    def get_hex(self, (screenx, screeny)):
        x = screenx - self._origo_position[0]
        y = screeny - self._origo_position[1]
        
        b = y / SCALE / SQRT_OF_THREE
        c = ((x / SCALE) - b) / 2.0
        a = b + c
        
        hex = pyciv.hexagon.get_hex(a, b, c)
        if hex in self._layout:
            return hex
        return None
